avatar

目录
pydantic cheatsheet

Here’s a comprehensive Pydantic cheatsheet that covers the most important features and use cases. This should serve as a quick reference for your future Pydantic projects.

Pydantic Cheatsheet

Pydantic Available Types

Pydantic’s BaseModel can contain a variety of specific types, allowing you to define models that validate and serialize data effectively. Here’s a breakdown of the types you can use in Pydantic models, including whether np.float (from NumPy) can be included.

Common Types in Pydantic

  1. Basic Types:

    • int: Integer values.
    • float: Floating-point numbers.
    • str: Strings.
    • bool: Boolean values.
  2. Optional Types:

    • Optional[type]: Indicates that a field can be of a specified type or None.
    • Example: Optional[str] means the field can be a string or None.
  3. Constrained Types:

    • conint: Constrained integer (e.g., conint(gt=0) for integers greater than 0).
    • confloat: Constrained float (e.g., confloat(ge=0.0) for floats greater than or equal to 0).
    • constr: Constrained string (e.g., constr(min_length=1) for non-empty strings).
  4. Collections:

    • List[type]: A list of items of a specified type.
    • Tuple[type1, type2]: A tuple with specified types.
    • Set[type]: A set of items of a specified type.
    • Dict[key_type, value_type]: A dictionary with specified key and value types.
  5. Custom Types:

    • You can define your own classes and use them as types in Pydantic models.
  6. Enums:

    • You can use Enum types to define a set of named constants.

Using NumPy Types

  • np.float: While Pydantic does not directly support NumPy types like np.float, you can use Python’s built-in float type instead. If you need to work with NumPy arrays or specific NumPy types, you can convert them to standard Python types when creating your Pydantic model.

Example of a Pydantic Model

Here’s an example of a Pydantic model using various types:

python
1
2
3
4
5
6
7
8
9
10
11
12
13
from pydantic import BaseModel, conint, confloat
from typing import List, Optional

class Item(BaseModel):
id: conint(gt=0) # Constrained integer
name: str
price: confloat(gt=0.0) # Constrained float
tags: List[str] # List of strings
description: Optional[str] # Optional string

# Example usage
item = Item(id=1, name="Sample Item", price=19.99, tags=["tag1", "tag2"])
print(item)

Summary

  • Pydantic’s BaseModel can contain various types, including basic types, constrained types, collections, custom types, and enums.
  • While np.float is not directly supported, you can use Python’s built-in float type for floating-point numbers.
  • If you need to work with NumPy types, consider converting them to standard Python types when creating your Pydantic models.

If you have any further questions or need more examples, feel free to ask!

Basic Model Definition

python
1
2
3
4
5
6
7
8
from pydantic import BaseModel, Field

class User(BaseModel):
id: int
name: str
email: str
age: int = Field(default=None, ge=0, lt=120)
is_active: bool = True

Field Types and Validations

python
1
2
3
4
5
6
7
from pydantic import BaseModel, Field, EmailStr, HttpUrl, constr

class AdvancedUser(BaseModel):
username: str = Field(..., min_length=3, max_length=50)
email: EmailStr
website: HttpUrl
password: constr(min_length=8, max_length=100)

Optional Fields and Default Values

python
1
2
3
4
5
6
7
from typing import Optional

class Product(BaseModel):
name: str
description: Optional[str] = None
price: float = Field(default=0.0, ge=0)
stock: int = 0

In Pydantic, the ge parameter in the Field function stands for “greater than or equal to.” You can use similar constraints to enforce various conditions on your fields. Here are some common constraints you can use:

  1. gt: Greater than
  2. lt: Less than
  3. le: Less than or equal to
  4. ge: Greater than or equal to (as you mentioned)
  5. min_length: Minimum length for strings
  6. max_length: Maximum length for strings
  7. regex: Regular expression for string validation
  8. multiple_of: Value must be a multiple of a specified number

Example Usage

Here’s how you might use some of these constraints in your Product model:

python
1
2
3
4
5
6
7
8
9
from pydantic import BaseModel, Field
from typing import Optional

class Product(BaseModel):
name: str
description: Optional[str] = None
price: float = Field(default=0.0, ge=0) # Price must be >= 0
stock: int = Field(default=0, ge=0) # Stock must be >= 0
sku: str = Field(..., min_length=5, max_length=10) # SKU must be between 5 and 10 characters

Explanation

  • ge=0: Ensures that the price and stock fields cannot be negative.
  • min_length=5: Ensures that the sku field has at least 5 characters.
  • max_length=10: Ensures that the sku field does not exceed 10 characters.

Nested Models

python
1
2
3
4
5
6
7
8
class Address(BaseModel):
street: str
city: str
country: str

class User(BaseModel):
name: str
address: Address

List and Dict Fields

python
1
2
3
4
5
from typing import List, Dict

class Order(BaseModel):
items: List[str]
quantities: Dict[str, int]

Custom Validators

python
1
2
3
4
5
6
7
8
9
10
11
from pydantic import BaseModel, validator

class User(BaseModel):
name: str
email: str

@validator('name')
def name_must_contain_space(cls, v):
if ' ' not in v:
raise ValueError('must contain a space')
return v.title()

Config and Behaviors

python
1
2
3
4
5
6
7
8
class User(BaseModel):
name: str
password: str

class Config:
allow_mutation = False
extra = 'forbid'
anystr_strip_whitespace = True

Field Aliases

python
1
2
3
class User(BaseModel):
name: str
email_address: str = Field(..., alias='email')

Dynamic Default Values

python
1
2
3
4
5
6
7
8
9
from datetime import datetime
from pydantic import BaseModel, Field

def get_current_time():
return datetime.now()

class LogEntry(BaseModel):
timestamp: datetime = Field(default_factory=get_current_time)
message: str

Type Coercion

python
1
2
3
4
5
6
7
8
9
class Model(BaseModel):
x: int
y: float
z: str

m = Model(x='1', y='2.5', z=3)
print(m.x) # 1 (int)
print(m.y) # 2.5 (float)
print(m.z) # '3' (str)

JSON Serialization/Deserialization

python
1
2
3
user_json = '{"name": "John", "email": "john@example.com"}'
user = User.model_validate_json(user_json)
json_string = user.model_dump_json()

Data Export

python
1
2
user_dict = user.model_dump()
user_json = user.model_dump_json()

Schema Generation

python
1
print(User.model_json_schema())

Custom Root Types

python
1
2
3
4
5
6
7
from pydantic import RootModel
from typing import List

class Users(RootModel):
root: List[User]

users = Users([User(name='Alice'), User(name='Bob')])

Enum Support

python
1
2
3
4
5
6
7
8
9
10
11
from enum import Enum
from pydantic import BaseModel

class Color(str, Enum):
RED = 'red'
GREEN = 'green'
BLUE = 'blue'

class Item(BaseModel):
name: str
color: Color

Date and Time Handling

python
1
2
3
4
5
6
7
from datetime import datetime, date, time
from pydantic import BaseModel

class Event(BaseModel):
start_date: date
start_time: time
end_datetime: datetime

Constrained Types

python
1
2
3
4
5
6
from pydantic import BaseModel, conint, constr, confloat

class Product(BaseModel):
id: conint(gt=0)
name: constr(min_length=3, max_length=50)
price: confloat(ge=0)

Error Handling

python
1
2
3
4
5
6
7
from pydantic import ValidationError

try:
product = Product(name='Sample Product', price=-10, stock=5) # Invalid price
except ValidationError as e:
print("Validation Error:")
print(e.errors()) # Print detailed error messages

Model Inheritance

python
1
2
3
4
5
6
class BaseUser(BaseModel):
id: int
username: str

class AdminUser(BaseUser):
admin_level: int

Field Descriptions

python
1
2
3
class User(BaseModel):
name: str = Field(..., description="The user's full name")
age: int = Field(..., description="The user's age in years")

Complex Validation with root_validator

python
1
2
3
4
5
6
7
8
9
10
11
12
from pydantic import BaseModel, root_validator

class Transaction(BaseModel):
amount: float
currency: str

@root_validator
def check_amount_currency(cls, values):
amount, currency = values.get('amount'), values.get('currency')
if amount > 1000 and currency == 'USD':
raise ValueError('USD transactions cannot exceed 1000')
return values

Load Yaml to Pydantic BaseModel Class

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import yaml
from pydantic import BaseModel

# Define the Pydantic model
class User(BaseModel):
name: str
age: int
email: str

# Load data from YAML file
with open('data.yaml', 'r') as file:
yaml_data = yaml.safe_load(file)

# Create an instance of the Pydantic model
user = User(**yaml_data)

# Print the user instance
print(user)

This cheatsheet covers a wide range of Pydantic features and use cases. It includes basic model definition, field types and validations, nested models, custom validators, configuration options, JSON handling, and more advanced features like custom root types and complex validations.

You can use this as a quick reference when working with Pydantic in your projects. Remember to import the necessary modules and classes as shown in the examples. As Pydantic evolves, some syntax or features might change, so it’s always a good idea to refer to the official documentation for the most up-to-date information.


评论